// 此为注册页面
import 'package:cloud_medicine/components/Input.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:cloud_medicine/http/user_api.dart';
import 'package:cloud_medicine/http/config.dart';
import 'package:cloud_medicine/components/sider_verify.dart';
import 'package:cloud_medicine/main.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

class LoginPage extends StatefulWidget {
  final String title;

  LoginPage({Key key, this.title}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  TextEditingController usernameController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  TextEditingController realnameController = TextEditingController();
  String errorUsernameText = '请使用数字或字母';
  String errorPasswordText = '请使用4位及其以上数字或字母';
  RegExp regUsername = RegExp(r"^[A-Za-z0-9]+$");
  RegExp regPassword = RegExp(r"^[A-Za-z0-9]{4,}$");
  RegExp regRealname = RegExp(r"^{,10}$");
  bool isPeople = false; // 人机验证结果
  int selectProfession = 3;
  final Map<int, String> identifyMap = {3: '患者', 4: '医生(需验证)', 5: '药店(需验证)'};
  List<int> _errorList = [];

  @override
  Widget build(BuildContext context) {
    Widget peopleVerify = Container(height: 0.0, width: 0.0); // 人机验证部件，默认为空

    if (widget.title == '登录') {
      peopleVerify = Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          SlideVerifyWidget(
            // 人机验证成功的函数
            verifySuccessListener: () {
              setState(() {
                isPeople = true;
              });
            },
            backgroundColor: Colors.grey[400],
          )
        ],
      );
    }

    // 动态改变单选框的组选择值
    void _changeRadioValue(int value) {
      setState(() {
        selectProfession = value;
      });
    }

    // 构建单选框
    Widget _buildRadio(int initValue) {
      return Wrap(
        crossAxisAlignment: WrapCrossAlignment.center,
        children: <Widget>[
          Radio(
            groupValue: selectProfession,
            activeColor: Colors.blue,
            value: initValue,
            onChanged: _changeRadioValue,
          ),
          Text(identifyMap[initValue]),
        ],
      );
    }

    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: SingleChildScrollView(
          child: Container(
            height: MediaQuery.of(context).size.height - 80, // TODO: 可能存在问题
            child: ListView(
              children: <Widget>[
                Column(
                  children: <Widget>[
                    SizedBox(height: 20),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Container(
                          width: 80,
                          height: 80,
                          child: Image.asset('images/logo.png'),
                        )
                      ],
                    ),
                    Text(
                      '云家医',
                      style: TextStyle(fontFamily: 'title', fontSize: 20),
                    )
                  ],
                ),
                ListView(
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  children: <Widget>[
                    SizedBox(height: 20),
                    Input(
                      textController: usernameController,
                      placeholder: '用户名',
                      isPassword: false,
                      normalErrorText: errorUsernameText,
                      reg: regUsername,
                      maxLines: 18,
                      errorList: _errorList,
                      index: 0,
                      setErrorList: setErrorList,
                    ),
                    SizedBox(height: 20),
                    widget.title == '注册'
                        ? Input(
                            textController: realnameController,
                            placeholder: '真实姓名',
                            isPassword: false,
                            normalErrorText: '',
                            reg: regRealname,
                            maxLines: 10,
                            errorList: _errorList,
                            index: 1,
                            setErrorList: setErrorList,
                          )
                        : Container(),
                    widget.title == '注册' ? SizedBox(height: 20) : Container(),
                    Input(
                      textController: passwordController,
                      placeholder: '密码',
                      isPassword: true,
                      normalErrorText: errorPasswordText,
                      reg: regPassword,
                      maxLines: 18,
                      errorList: _errorList,
                      index: 2,
                      setErrorList: setErrorList,
                    ),
                    SizedBox(height: 30),
                    widget.title == '注册'
                        ? Wrap(
                            // direction: Axis.horizontal,
                            // alignment: WrapAlignment.spaceBetween,
                            children: <Widget>[
                              _buildRadio(3),
                              _buildRadio(4),
                              _buildRadio(5),
                            ],
                          )
                        : Container(),
                  ],
                ),
                peopleVerify,
                SizedBox(height: 20),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    RaisedButton(
                      onPressed: login,
                      textColor: Colors.white,
                      color: Colors.blueAccent,
                      child: Text('${widget.title}'),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ));
  }

  void setErrorList(List<int> errorList) {
    setState(() {
      _errorList = errorList;
    });
  }

  void login() async {
    if (!isPeople && widget.title == '登录') {
      Fluttertoast.showToast(msg: '未进行登录验证');
      return;
    }

    if(_errorList.length > 0) {
      errorToast('请按照要求填写');
      return;
    }
    dynamic res;

    if (widget.title == '注册') {
      res = await enroll_api({
        'realname': realnameController.text,
        'username': usernameController.text,
        'password': generateMd5(passwordController.text),
        'identify_id': selectProfession,
      });
    } else {
      res = await login_api('$backIP/user/login', {
        'username': usernameController.text,
        'password': generateMd5(passwordController.text),
        'isAdmin': false
      });
    }

    if (res['code'] != 0) {
      errorToast(res['message']);
      return;
    } else {
      successToast(res['message']);
    }

    await getBasicUserInfo_api();
    // 进入主页面的我的页面
    Navigator.of(context).push(
      new MaterialPageRoute(builder: (context) => MyHomePage(initIndex: 4)),
    );
  }
}
